﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
using YmtAuth.Domain;
using YmtAuth.Domain.Repository;
using YmtSystem.CrossCutting;
using YmtAuth.Dto;

namespace YmtAuth.Repository.MySQL
{
    public class DualSecurityRepository : MySQLRepository<DualSecurity>, IDualSecurityRepository
    {
        private static ISecurityQuestionRepository securityQuestionRepo { get { return LocalServiceLocator.GetService<ISecurityQuestionRepository>(); } }
        
        public DualSecurityRepository()
            : base(ConfigurationManager.AppSettings["SecurityQuestion_MySQLConnString"], "userdualsecurity")
        {

        }

        /// <summary>
        /// 查询双重验证
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public DualSecurity GetDualSecurityResult(int userId)
        {
            DualSecurity dualSecurity = null;
            try
            {
                string selectSQL = "select UserId, Enable, CreateTime, LastUpdateTime from userdualsecurity where userid = @userid";
                DynamicParameters selectPar = this.Parameters.AddInt("@userid", userId).Build();

                IEnumerable<DualSecurity> list = null;

                using (var conn = new MySqlConnection(ConfigurationManager.AppSettings["SecurityQuestion_MySQLConnString"]))
                {
                    list = conn.Query<DualSecurity>(selectSQL, selectPar, commandType: CommandType.Text);
                }

                if (list != null && list.Any())
                {
                    dualSecurity = list.OrderByDescending(r => r.LastUpdateTime).First();
                }
            }
            catch (Exception ex)
            {
                YmatouLoggingService.Error(string.Format("[GetDualSecurityResult] error, user: {0}; errormsg: {1}", userId, ex.Message), ex);
            }

            return dualSecurity;
        }

        /// <summary>
        /// 设置双重验证
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public ResponseData<bool> SetDualSecurity(int userId, bool enable)
        {
            ResponseData<bool> res = null;

            try
            {
                DualSecurity dualSecurity = GetDualSecurityResult(userId);

                if (dualSecurity == null)
                {
                    var insertSql = "INSERT INTO userdualsecurity (UserId, Enable, CreateTime, LastUpdateTime) VALUES (@userid, @enable, @createtime, @lastupdatetime)";

                    DateTime now = DateTime.Now;
                    DynamicParameters par = this.Parameters.AddInt("@userid", userId).AddInt("@enable", enable ? 1 : 0).AddDateTime("@createtime", now).AddDateTime("@lastupdatetime", now).Build();
                    using (var conn = new MySqlConnection(ConfigurationManager.AppSettings["SecurityQuestion_MySQLConnString"]))
                    {
                        var affectedRows = conn.Execute(insertSql, par, commandType: CommandType.Text);
                        YmatouLoggingService.Debug("[SetDualSecurity] insert user {0} dual security, enable: {1}, affected: {2} rows", userId, enable, affectedRows);
                    }

                    res = ResponseData<bool>.Create(true, true, "ok", "200");
                }
                else
                {
                    if (dualSecurity.Enable == enable)
                    {
                        res = ResponseData<bool>.Create(true, true, "ok", "202");
                        YmatouLoggingService.Debug("[SetDualSecurity] no need to update, user {0}", userId);
                    }
                    else
                    {
                        var updateSQL = "UPDATE userdualsecurity SET Enable = @enable WHERE UserId = @userid";

                        DynamicParameters par = this.Parameters.AddInt("@userid", userId).AddInt("@enable", enable ? 1 : 0).Build();

                        using (var conn = new MySqlConnection(ConfigurationManager.AppSettings["SecurityQuestion_MySQLConnString"]))
                        {
                            var affectedRows = conn.Execute(updateSQL, par, commandType: CommandType.Text);
                            YmatouLoggingService.Debug("[SetDualSecurity] update user {0} dual security, enable: {1}, affected: {2} rows", userId, enable, affectedRows);
                        }

                        res = ResponseData<bool>.Create(true, true, "ok", "201");
                    }
                }
            }
            catch (Exception ex)
            {
                res = ResponseData<bool>.Create(false, false, "设置双重验证出现异常, " + ex.Message, "500");
                YmatouLoggingService.Error("[SetDualSecurity] error, user: {0}", userId);
            }

            return res;
        }
    }
}
